package com.imon.web.codesphere.resources;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.tmatesoft.svn.core.SVNException;

import com.imon.web.codesphere.data.RepositoryInfo;

@Path("/admin")
@Component
public class AdminResource extends ResourceBase {

	private static final Log LOG = LogFactory.getLog(AdminResource.class);

	@POST
	@Path("/repositories")
	@Produces(MediaType.TEXT_PLAIN)
	public Response newRepository(@FormParam("title") final String title, @FormParam("location") final String location,
			@FormParam("username") final String username, @FormParam("password") final String password) {
		LOG.debug(String.format("newRepository(%s, %s, %s, %.2s)", title, location, username, password));

		try {
			final RepositoryInfo remoteRepositoryInfo = getRepositoryGateway().addRepository(title, location, username,
					password);

			processRepositoryInBackground(remoteRepositoryInfo);

		} catch (final SVNException e) {
			LOG.error(String.format("Error adding repository: %s", location), e);
		}

		return Response.ok("Repository Added").build();
	}

	private void processRepositoryInBackground(final RepositoryInfo remoteRepositoryInfo) {
		getExecutor().execute(new Runnable() {

			@Override
			public void run() {
				try {
					getRepositoryGateway().processRepository(remoteRepositoryInfo);
				} catch (final SVNException e) {
					LOG.error(String.format("Error processing repository:", remoteRepositoryInfo.getLocation()), e);
				}
			}
		});

	}
}
